package com.bite.blog.config;


import com.bite.blog.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice{  //统一结果 返回
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {  //判断是否要执⾏beforeBodyWrite⽅法,true为执⾏,false不执⾏.
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof Result) {  //如果是result返回类型就不用再进行包装了
            return body;
        }

        if (body instanceof String) {  //如果是String返回类型,使⽤SpringBoot内置提供的Jackson来实现信息的序列化
            return objectMapper.writeValueAsString(Result.success(body));
        }
        //对response⽅法进⾏具体操作处理
        return Result.success(body);

    }
}
